<script setup lang="ts">
import {getCurrentInstance, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import SideBar from "./components/SideBar.vue";
import {useRoute} from 'vue-router';
import ThirdPartyAccounts from "./components/ThirdPartyAccounts.vue";
import {EmailControllerService, EmailInfoVO, UserControllerService} from "../../../generated";
import PhoneEdit from "./components/PhoneEdit.vue";

// 添加控制编辑区域显示的状态
const showEmailEdit = ref(false);
const showPhoneEdit = ref(false);
const showPasswordEdit = ref(false);

// 添加手机编辑对话框可见性状态
const phoneEditVisible = ref(false);

const instance = getCurrentInstance();
if (!instance) {
  throw new Error('Component instance is null');
}

interface ComponentInstance {
  $Encrypt: (password: string) => string;
}

const proxy = instance.proxy as unknown as ComponentInstance;

// 修改表单数据，添加当前显示值
const form = reactive({
  currentEmail: '',
  currentPhone: '',
  email: '',
  phone: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  isEmailVerified: false,
  isEmailPrimary: false
});

const rules = {
  email: [
    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能小于6位', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value !== form.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

const formRef = ref();

// 添加新的响应式数据
const emailList = ref<Array<EmailInfoVO>>([]);

const loadUserInfo = async () => {
  const res = await UserControllerService.getUserSecureInfoUsingGet();
  // 重置邮箱列表
  emailList.value = [];
  if (res.code === 0 && res.data) {
    // 处理邮箱信息
    const emails = res.data.displayEmail;
    if (Array.isArray(emails) && emails.length > 0) {
      emailList.value = emails;

      // 优先使用主邮箱，如果没有则使用第一个邮箱
      const displayEmail = emails.find(email => email.isPrimary) || emails[0];
      updateEmailDisplay(displayEmail);
    } else {
      updateEmailDisplay();
    }
    // 设置手机号
    form.currentPhone = res.data.displayPhone || '未设置';
  }
};

// 辅助函数：更新邮箱显示信息
const updateEmailDisplay = (email?: EmailInfoVO) => {
  form.currentEmail = email?.email ?? '未设置';
  form.isEmailVerified = email?.isVerified ?? false;
  form.isEmailPrimary = email?.isPrimary ?? false;
};

const handleUpdateEmail = async () => {
  try {
    await formRef.value.validateField('email');
    // 调用添加邮箱的API
    const res = await UserControllerService.addEmailUsingPost({
      email: form.email
    });
    if (res.code === 0) {
      // 添加新邮箱到列表中
      emailList.value.push({
        id: res.data.id,
        email: form.email,
        isPrimary: false,
        isVerified: false
      });
      form.email = ''; // 清空输入框
      ElMessage.success('邮箱添加成功，请查收验证邮件');
    }
  } catch (error) {
    ElMessage.error('添加邮箱失败');
  }
};

const handleUpdatePhone = async () => {
  // 显示手机号修改对话框
  phoneEditVisible.value = true;
};

// 添加手机号更新成功回调
const handlePhoneUpdateSuccess = async () => {
  await loadUserInfo();
  ElMessage.success('手机号更新成功');
};

const handleUpdatePassword = async () => {
  await formRef.value.validateField(['oldPassword', 'newPassword', 'confirmPassword']);

  let oldPassword = proxy.$Encrypt(form.oldPassword);
  let newPassword = proxy.$Encrypt(form.newPassword);
  let res = await UserControllerService.updatePasswordUsingPost({
    oldPassword: oldPassword,
    newPassword: newPassword
  });
  if (res.code === 0) {
    showPasswordEdit.value = false;
    form.oldPassword = '';
    form.newPassword = '';
    form.confirmPassword = '';
    ElMessage.success('密码更新成功');
  } else {
    ElMessage.error(res.message || '密码更新失败')
  }
};

const cancelEdit = (type: 'email' | 'phone' | 'password') => {
  if (type === 'email') {
    showEmailEdit.value = false;
    form.email = '';
  } else if (type === 'phone') {
    showPhoneEdit.value = false;
    form.phone = '';
  } else {
    showPasswordEdit.value = false;
    form.oldPassword = '';
    form.newPassword = '';
    form.confirmPassword = '';
  }
};

const thirdPartyAccountsRef = ref();

// 处理URL参数
const route = useRoute();
onMounted(async () => {
  await loadUserInfo();

  // 原有的处理URL参数逻辑
  const success = route.query.success;
  const error = route.query.error;

  if (success === 'true') {
    ElMessage.success('GitHub账号绑定成功');
    // 更新绑定状态
    thirdPartyAccountsRef.value?.updateBindStatus();
  } else if (error) {
    const errorMessages: Record<string, string> = {
      'invalid_state': '非法的请求',
      'not_bound': 'GitHub账号未绑定',
      'not_login': '请先登录',
      'github_error': '获取GitHub用户信息失败',
      'invalid_type': '无效的操作类型'
    };
    ElMessage.error(errorMessages[error as string] || '因众所周知的原因，请稍后再试');
  }
});

// 添加设为主邮箱的方法
const setPrimaryEmail = async (id: string) => {
  try {
    const res = await EmailControllerService.modifyPrimaryEmailUsingPost({
      id: String(id)
    });
    if (res.code === 0) {
      await loadUserInfo();
      ElMessage.success('已成功设置为主邮箱');
    } else {
      ElMessage.error(res.message || '设置主邮箱失败');
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('设置主邮箱失败');
  }
};

// 添加重新发送验证邮件的方法
const resendVerification = async (id: string) => {
  try {
    const res = await EmailControllerService.resendVerificationEmailUsingPost({
      id: String(id)
    });
    if (res.code === 0) {
      ElMessage.success('验证邮件已发送，请查收');
    } else {
      ElMessage.error(res.message || '发送验证邮件失败');
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('发送验证邮件失败');
  }
};

// 添加删除邮箱的方法
const deleteEmail = async (id: string) => {
  ElMessageBox.confirm(
      '是否删除邮箱?该操作无法撤回',
      'warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const res = await EmailControllerService.deleteEmailUsingPost({
          id: String(id)
        });
        if (res.code === 0) {
          await loadUserInfo();
          ElMessage.success('邮箱删除成功');
        } else {
          ElMessage.error(res.message || '删除邮箱失败');
        }
      })
};
</script>

<template>
  <div class="profile-container">
    <SideBar/>
    <div class="profile-edit">
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <div class="title">账号信息</div>
        <el-divider/>

        <div class="info-item">
          <div class="info-header">
            <span class="info-label">电子邮箱</span>
            <div class="info-content">
              <span>{{ form.currentEmail }}</span>
              <el-tag v-if="form.isEmailPrimary" size="small" type="primary" round>主邮箱</el-tag>
              <el-tag v-if="!form.isEmailVerified" size="small" type="danger" round>未验证</el-tag>
              <el-button link type="primary" @click="showEmailEdit = true" v-if="!showEmailEdit">
                修改
              </el-button>
            </div>
          </div>
          <div class="edit-area" v-if="showEmailEdit">
            <div v-if="emailList.length > 0" class="email-list">
              <div v-for="item in emailList" :key="item.id" class="email-item">
                <div class="email-info">
                  <span>{{ item.email }}</span>
                  <div class="email-tags">
                    <el-tag v-if="item.isPrimary" size="small" type="primary" round>主邮箱</el-tag>
                    <el-tag v-if="!item.isVerified" size="small" type="danger" round>未验证</el-tag>
                  </div>
                </div>
                <div class="email-actions">
                  <el-button
                      v-if="!item.isPrimary"
                      link
                      type="primary"
                      @click="item.id && setPrimaryEmail(item.id)"
                  >
                    设为主邮箱
                  </el-button>
                  <el-button
                      v-if="!item.isVerified"
                      link
                      type="primary"
                      @click="item.id && resendVerification(item.id)"
                  >
                    重新发送验证邮件
                  </el-button>
                  <el-button
                      v-if="!item.isPrimary"
                      link
                      type="danger"
                      @click="item.id && deleteEmail(item.id)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
            <el-form-item prop="email">
              <el-input v-model="form.email" placeholder="请输入新的邮箱地址"/>
            </el-form-item>
            <div class="button-group">
              <el-button @click="cancelEdit('email')">取消</el-button>
              <el-button type="primary" @click="handleUpdateEmail">确认</el-button>
            </div>
          </div>
        </div>

        <div class="info-item">
          <div class="info-header">
            <span class="info-label">手机号码</span>
            <div class="info-content">
              <span>{{ form.currentPhone }}</span>
              <el-button link type="primary" @click="handleUpdatePhone" v-if="!showPhoneEdit">
                修改
              </el-button>
            </div>
          </div>
        </div>

        <div class="info-item">
          <div class="info-header">
            <span class="info-label">登录密码</span>
            <div class="info-content">
              <span>已设置</span>
              <el-button link type="primary" @click="showPasswordEdit = true" v-if="!showPasswordEdit">
                修改
              </el-button>
            </div>
          </div>
          <div class="edit-area" v-if="showPasswordEdit">
            <el-form-item prop="oldPassword">
              <el-input
                  v-model="form.oldPassword"
                  type="password"
                  placeholder="请输入当前密码"
                  show-password
              />
            </el-form-item>
            <el-form-item prop="newPassword">
              <el-input
                  v-model="form.newPassword"
                  type="password"
                  placeholder="请输入新密码"
                  show-password
              />
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                  v-model="form.confirmPassword"
                  type="password"
                  placeholder="请确认新密码"
                  show-password
              />
            </el-form-item>
            <div class="button-group">
              <el-button @click="cancelEdit('password')">取消</el-button>
              <el-button type="primary" @click="handleUpdatePassword">确认</el-button>
            </div>
          </div>
        </div>

        <div class="title">关联账号</div>
        <el-divider/>
        <ThirdPartyAccounts ref="thirdPartyAccountsRef"/>
      </el-form>
    </div>

    <PhoneEdit
        v-model="phoneEditVisible"
        @close="phoneEditVisible = false"
        @success="handlePhoneUpdateSuccess"
    />
  </div>
</template>

<style scoped>
.profile-container {
  display: flex;
  gap: 20px;
  max-width: 1000px;
  margin: 20px auto;
  padding: 0 20px;
}

.profile-edit {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  max-width: none;
  margin: 0;
}

.title {
  font-size: 16px;
  color: rgba(0, 0, 0, 1);
  line-height: 48px;
  height: 48px;
  font-weight: bold;
}

.info-item {
  padding: 24px 0;
  border-bottom: 1px solid #eee;
}

.info-item:last-child {
  border-bottom: none;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-label {
  font-size: 14px;
  color: #606266;
}

.info-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.info-content span {
  font-size: 14px;
}

.edit-area {
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}

:deep(.el-divider) {
  margin: 0;
}

.email-list {
  margin-bottom: 16px;
}

.email-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.email-item:last-child {
  border-bottom: none;
}

.email-info {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.email-tags {
  display: flex;
  gap: 8px;
}

.email-actions {
  display: flex;
  gap: 12px;
}
</style>